<?php

namespace app\admin\controller;

use app\logic\DataHelper;
use app\logic\MenuHelper;
use think\facade\Cache;
use think\facade\Db;
use think\facade\View;
use think\helper\Str;

class Frame extends Base
{
    public function index() {
        $admin = get_curr_admin();
        $all_menu_list = DataHelper::select('tb_menu', "status=0",
            [
                'with_power' => false,
                'order_by' => 'idx desc'
            ]);
        $menu_list = MenuHelper::load_role_menu(0, $admin['role_id'], $all_menu_list);

        return View::fetch('index', [
            'menu_list' => $menu_list,
            'admin' => $admin
        ]);
    }

    public function info() {
        $admin = get_curr_admin();

        return View::fetch('info', [
            'admin' => $admin
        ]);
    }

    public function changepwd() {
        return View::fetch('changepwd');
    }

    public function save_pwd() {
        $params = get_all_params();

        if (!check_params_empty(['oldPassword', 'password', 'repassword'])) {
            return json([ 'code' => -1, 'msg' => '请填写：当前密码,新密码,确认密码' ]);
        }

        $admin = get_curr_admin();
        if ($admin['password'] != md5($params['oldPassword'])) {
            return json([ 'code' => -1, 'msg' => '请填写：当前密码错误' ]);
        }

        DataHelper::update('tb_admin', "id=".$admin['id'], [
            'password' => md5($params['password'])
        ]);

        return json([ 'code' => 0, 'msg' => '成功' ]);
    }

    public function login() {
        $token = cookie("admin_token");
        if (!empty($token)) {
            Cache::delete($token);
        }

        //return 'ok';
        return View::fetch('login');
        //return view('login');
    }

    public function login_submit() {
        $params = get_all_params();

        if (!check_params_empty(['login_name', 'password'])) {
            return json([ 'code' => -1, 'msg' => '请填写：登录名,密码' ]);
        }

        $login_name = $params['login_name'];
        $password = $params['password'];

        $list = DataHelper::select('tb_admin', [ [ "login_name", "=", $login_name ] ]);
        if (count($list) == 0) {
            return json([ 'code' => -1, 'msg' => '登录名不存在' ]);
        }

        $admin = $list[0];
        if ($admin['password'] != md5($password)) {
            return json([ 'code' => -1, 'msg' => '密码错误' ]);
        }

        //登录成功，生成token
        $token = Str::random(258);

        Cache::set($token, $admin, 3600);
        cookie("admin_token", $token);

        return json([ 'code' => 0, 'msg' => '成功', 'token' => $token ]);
    }


    public function home() {
        return View::fetch('home');
    }
}